#include "meter.h"
#include <stdio.h>
#include <syslog.h>

int bitval[]={0,
	      UEIB_INP1,
	      UEIB_INP2,
	      UEIB_INP3,
	      UEIB_INP4,
	      UEIB_INP5
	      };

/*
 * poll_meters
 * polls the digital inputs of the k8085 and updates the meter readings
 * where necessary
 * 05feb2006  GJ  ORIGINAL VERSION
 */
int poll_meters() {
  int i,value;
  int bit;

  ueib_update(uh);
  for (i=0;i<n_meter;i++) {
    bit = bitval[meters[i].input];
    value = ueib_get_dig_input(uh,bit);
    if (meters[i].lastval==1 && value == 0) {
      meters[i].reading = meters[i].reading + meters[i].cfac;
      syslog(LOG_INFO,"Meter %d Reading = %6.3lf\n",i,meters[i].reading);
    }
    meters[i].lastval = value;
  }
}


/*
 * open_iocard(int cardno)
 * initialises the k8085 IO card number cardno for input/output
 * the global variable uh is set as the handle to access the card.
 *
 * 06feb2006  GJ  ORIGINAL VERSION
 */ 
int open_iocard(int cardno) {
  syslog(LOG_INFO,"open_iocard - cardno=%d\n",cardno);
  usb_init();
  uh = ueib_init(cardno);
  if (uh==NULL) 
    {
      syslog(LOG_ERR, "Error initialising k8085 device number %d\n",cardno);
      return -1;
    }
  else
    {
      syslog(LOG_INFO,"opened card ok\n");
      return 0;
    }
}

/*
 * close_iocard
 * closes the k8085 card pointed to by global variable uh neatly.
 *
 * 06feb2006  GJ  ORIGINAL VERSION
 */
int close_iocard() {
  ueib_close(uh);
    return 0;

}
